package com.lxyk.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.lxyk.pojo.Account;
import com.lxyk.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.servlet.http.HttpSession;

/*bug:java.nio.charset.MalformedInputException: Input length = 1这是因为yml默认编码为GBK 只要在 setting的file encoding 把yml文件
* 的编码改为UTF-8即可 改完之后有时候还会有提示 这时候只要去掉乱码的注释即可*/
@Controller
public class AccountController {
    @Autowired
    private AccountService accountService;
    @PostMapping("/login")
    public String login(String userName, String userPwd, Model model,HttpSession session){
        Boolean result = accountService.login(userName, userPwd);
        if (result){
            //登录成功 跳转到主页
            session.setAttribute("currentUser",userName);
            return "waterMainMenu";
        }else {
            model.addAttribute("msg","用户名或密码错误！");
            return "index";
        }
    }
    //返回首页功能
    /*bug:Request method 'GET' not supported这是因为我们的前端页面<a class="btn btn-info" th:href="@{/hello}">回到首页</a>
    * 是a标签href 不是action href是直接访问一个网页 直接去网页发送请求默认都是get 所以这里用PostMapping会报错 你可以用GetMapping
    * 也可以用RequestMapping RequestMapping在不设置method参数的情况下同时支持get和post*/
    @RequestMapping("/hello")
    public String hello(){
        return "waterMainMenu";
    }

    @RequestMapping("/pwd")
    public String pwd(){
        return "modify";
    }

    @RequestMapping("/pwdUser")
    public String pwdUser(String userPwd,String newPwd,Model model,HttpSession session){
        String userName = (String) session.getAttribute("currentUser");
        Boolean login = accountService.login(userName, userPwd);
        if (login){
            Account account=new Account();
            account.setUserName(userName);
            newPwd = DigestUtil.md5Hex(newPwd);
            account.setUserPwd(newPwd);
            boolean b = accountService.pwdUser(account);
            if (b){
                return "index";//修改密码成功 跳转到登录页面
            }else {
                model.addAttribute("loginFail","修改密码失败!");
                model.addAttribute("currentUser",session.getAttribute("currentUser"));
            }
        }else {
            model.addAttribute("loginFail","修改密码失败！");
        }
        return "modify";
    }
    /*修改修改密码页面背景图片 1.把图片放到img 在css中修改路径 2.不行就把target删掉再运行 3.还不行就ctrl+shift+del清理缓存*/

}
